﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShareMarking.Systems.Service;
using ShareMarking.Service;
using ShareMarking.Entity;
using System.Configuration;
using System.Text.RegularExpressions;

namespace ShareMarking.Web.admin.EnterPrise.QrStore
{
    public partial class Action : ManagePage
    {
        #region 属性=====================================
        private static string diyhttp = ConfigurationManager.AppSettings["diyhttp"];//本系统网站域名
        /// <summary>
        /// 门店编码
        /// </summary>
        protected String Par_S_Code
        {
            get { return txt_S_Code.Text; }
            set { txt_S_Code.Text = value; }
        }

        /// <summary>
        /// 门店名称
        /// </summary>
        protected String Par_S_Name
        {
            get { return txt_S_Name.Text; }
            set { txt_S_Name.Text = value; }
        }

        /// <summary>
        /// 门店所属省份
        /// </summary>
        protected String Par_S_Provinces
        {
            get { return txt_S_Provinces.Text; }
            set { txt_S_Provinces.Text = value; }
        }

        /// <summary>
        /// 门店所属城市
        /// </summary>
        protected String Par_S_City
        {
            get { return txt_S_City.Text; }
            set { txt_S_City.Text = value; }
        }

        /// <summary>
        /// 门店所属片区
        /// </summary>
        protected String Par_S_Area
        {
            get { return txt_S_Area.Text; }
            set { txt_S_Area.Text = value; }
        }

        /// <summary>
        /// 门店所属大区
        /// </summary>
        protected String Par_S_Region
        {
            get { return txt_S_Region.Text; }
            set { txt_S_Region.Text = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        protected String Par_A_wxTitle
        {
            get { return txt_A_wxTitle.Text; }
            set { txt_A_wxTitle.Text = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        protected String Par_A_wxImgUrl
        {
            get { return txt_A_wxImgUrl.Text; }
            set { txt_A_wxImgUrl.Text = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        protected String Par_A_wxDesc
        {
            get { return txt_A_wxDesc.Text; }
            set { txt_A_wxDesc.Text = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        protected String Par_A_wxUrl
        {
            get { return txt_A_wxUrl.Text; }
            set { txt_A_wxUrl.Text = value; }
        }

        #endregion

        #region 初始化===================================

        protected string action = DTEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            string _action = DTRequest.GetQueryString("action");
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                this.action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                this.id = DTRequest.GetQueryInt("id");
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back", "Error");
                    return;
                }
                if (!qr_StoreService.Instance.Get_IsExist_ByWhere(qr_Store._.id == this.id))
                {
                    JscriptMsg("信息不存在或已被删除！", "back", "Error");
                    return;
                }
            }
            if (!Page.IsPostBack)
            {
                //ChkAdminLevel("user_list", DTEnums.ActionEnum.View.ToString()); //检查权限

                //绑定下拉框

                if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
                {
                    ShowInfo(this.id);
                }
            }
        }

        #endregion

        #region 绑定下拉框===============================


        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            var entity = qr_StoreService.Instance.Get_SingleEntity_byWhere(qr_Store._.id == _id);
            if (entity == null) return;
            Par_S_Code = entity.StoreCode;
            Par_S_Name = entity.S_Name;
            Par_S_Provinces = entity.S_Provinces;
            Par_S_City = entity.S_City;
            Par_S_Area = entity.S_Area;
            Par_S_Region = entity.S_Region;
            this.iImagesurl.ImageUrl = entity.A_wxImgUrl;
            Par_A_wxTitle = entity.A_wxTitle;
            Par_A_wxDesc = entity.A_wxDesc;
            Par_A_wxImgUrl = entity.A_wxImgUrl;
            Par_A_wxUrl = entity.A_wxUrl;
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            if (Par_S_Code.IsNullOrEmpty())
            {
                JscriptMsg("请输入门店编号！", "", "Error");
                return false;
            }
            if (qr_StoreService.Instance.Get_IsExist_ByWhere(qr_Store._.StoreCode == Par_S_Code))
            {
                JscriptMsg("门店编号已经存在！", "", "Error");
                return false;
            }

            var httpstr = ConfigurationManager.AppSettings["vigohttp"];
            var signsecret = ConfigurationManager.AppSettings["signscrect"];
            var result = false;

            #region 添加门店二维码

            #region 组装消息
            var sceneid = 0;
            qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID == 1002);
            sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;

            #region 2016-10-8弃用组装消息
            //var extra = new List<ShareMarking.Interface.extra>() { 
            //    new ShareMarking.Interface.extra { 
            //        //title = Par_A_wxTitle, 
            //        //shortdesc = Par_A_wxDesc, 
            //        //linkurl = Par_A_wxUrl.Replace('&','$'),
            //        //picurl ="http://admin.mjn.c2d.me/"+ Par_A_wxImgUrl
            //        title="美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享",
            //        shortdesc="",
            //        linkurl="http://wx.ismartgo.com/app/lighthouse/index.aspx?from="+Par_S_Code+"$type=2$openid=####",
            //        picurl="http://qrcode.mjn.howjoin.com/imgforweixin/activity.jpg"
            //    }
            //};
            #endregion

            string currenturl = Regex.Replace(txt_A_wxUrl.ToString().Trim(), @"\s", "");
            #region 编辑图文信息
            var extra = new List<ShareMarking.Interface.extra>() { 
                    new ShareMarking.Interface.extra { 
                        title = Par_A_wxTitle, 
                        shortdesc = Par_A_wxDesc, 
                        linkurl = (currenturl).Replace('&','$'),
                        picurl =diyhttp+ Par_A_wxImgUrl
                    }
                   };
            //var extra = new List<ShareMarking.Interface.extra>() {
            //                new ShareMarking.Interface.extra { 
            //                            title = "马上加入蓝臻积分臻赏荟，百种臻礼等你来兑", 
            //                            shortdesc = "", 
            //                            linkurl = "https://lhloyalty.otype.com/?shopId="+o.StoreCode+"$shopName="+o.S_Name+"", //?regSubChannel=174$PNRCode="+o.EmployeeNumber__c+"$openId=####",
            //                            picurl = "http://admin.mjn.howjoin.com/images/store.jpg" 
            //                        }                                
            //                };
            //var extra = new List<ShareMarking.Interface.extra>() { 
            //                        new ShareMarking.Interface.extra { 
            //                            title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
            //                            shortdesc = "一键注册，终身礼遇", 
            //                            linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
            //                            picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
            //                        },
            //                        new ShareMarking.Interface.extra{
            //                            title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
            //                            shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
            //                            linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
            //                            picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
            //                        },
            //                        new ShareMarking.Interface.extra{
            //                            title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
            //                            shortdesc = "惊喜连连，准备好了么？", 
            //                            linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
            //                            picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
            //                        }
            //                    };
            #endregion

            var message = new ShareMarking.Interface.message()
            {
                title = Par_S_Name,
                remark = Par_S_Name + "的二维码",
                sacode = "test",
                scene_id = sceneid,
                extra = extra
            };
            #endregion

            #region vigo接口申请
            var vigo = new ShareMarking.Interface.Qrcode_vigo(httpstr, signsecret);
            var resultentity = vigo.CreateQrcode(message);
            #endregion

            #region 自增sceneid重新请求直到成功为止
            while (resultentity.errcode == "12")
            {
                ComLib.LogLib.Log4NetBase.Log("错误信息:" + resultentity.errmsg + "/sceneid=" + sceneid);
                sceneid += 1;
                message.scene_id = sceneid;
                resultentity = vigo.CreateQrcode(message);
            }
            #endregion

            if (resultentity.errcode == "00")
            {
                #region 保存二维码到数据库
                qr_QrCode qrcode = new qr_QrCode()
                {
                    id = resultentity.message.id,
                    type = 1002,
                    scene_id = resultentity.message.scene_id,
                    sacode = resultentity.message.sacode,
                    title = resultentity.message.title,
                    remark = resultentity.message.remark,
                    code_url = resultentity.message.code_url,
                    qrcode_url = resultentity.message.qrcode_url,
                    addtime = resultentity.message.addtime,
                    status = resultentity.message.status,
                    isdelete = false
                };
                qr_QrCodeService.Instance.Add_Entity(qrcode);
                #endregion

                #region 保存门店
                var entity = new qr_Store();
                entity.StoreCode = Par_S_Code;
                entity.S_Name = Par_S_Name;
                entity.S_Provinces = Par_S_Provinces;
                entity.S_City = Par_S_City;
                entity.S_Area = Par_S_Area;
                entity.S_Region = Par_S_Region;
                entity.CreateOn = DateTime.Now;
                entity.A_wxQrCodeID = resultentity.message.id.ToString();
                entity.A_wxSceneID = resultentity.message.scene_id.ToString();
                entity.A_wxTitle = "马上加入蓝臻积分臻赏荟，百种臻礼等你来兑";//"美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享";
                entity.A_wxDesc = "";
                entity.A_wxUrl = "https://lhloyalty.otype.com/?shopId=" + Par_S_Code + "$shopName=" + Par_S_Name + "";//"http://wx.ismartgo.com/app/lighthouse/index.aspx?from=" + Par_S_Code + "$type=2$openid=####";
                entity.A_wxImgUrl = Par_A_wxImgUrl;//"http://admin.mjn.howjoin.com/images/store.jpg";//"http://qrcode.mjn.howjoin.com//imgforweixin/activity.jpg";
                entity.Remark = "蓝臻积分";
                entity.isneedupdate = true;
                entity.isneedupload = true;
                result = qr_StoreService.Instance.Add_Entity(entity);
                #endregion

                #region 添加关联
                qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                {
                    qr_Type = 1002,//1000是活动
                    qr_CodeID = resultentity.message.id,
                    qr_Scene_ID = resultentity.message.scene_id,
                    rel_Code = entity.StoreCode.ToString(),
                    IsDelete = false,
                    CreateOn = DateTime.Now
                };
                qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                #endregion

                #region 更改二维码类型表
                type.QT_CurrentIndex = sceneid;
                type.QT_Used = type.QT_Used + 1;
                type.QT_Surplus = type.QT_Surplus - 1;
                result = qr_QrCodeTypeService.Instance.Update_Entity(type);
                #endregion

                if (result)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加qr_Store:" + entity.StoreCode); //记录日志
                }
            }
            #endregion
            return result;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
             var entity =qr_StoreService.Instance.Get_SingleEntity_byWhere(qr_Store._.id == _id);
            if (entity == null) return false;
            var result = false;
            var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                                qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                                && qr_QrCodeRelate._.rel_Code == entity.StoreCode);
            if (relate != null)
            { 
                var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == relate.qr_CodeID);
                if (qrcode != null)
                {
                    #region 修改活动二维码
                    var httpstr = ConfigurationManager.AppSettings["vigohttp"];
                    var signsecret = ConfigurationManager.AppSettings["signscrect"];
                   
                    string A_wxUrl = "https://lhloyalty.otype.com/?shopId=" + Par_S_Code + "$shopName=" + Par_S_Name + "";
                    #region 组装消息
                    var extra = new List<ShareMarking.Interface.extra>() { 
                                new ShareMarking.Interface.extra { 
                                    title = Par_A_wxTitle, 
                                    shortdesc = Par_A_wxDesc, 
                                    linkurl = Regex.Replace(A_wxUrl.ToString().Trim(), @"\s", "").Replace('&','$'),
                                    picurl =diyhttp+Par_A_wxImgUrl
                                }
                            };
                    var message = new ShareMarking.Interface.message2()
                    {
                        id = qrcode.id.ToString(),
                        title = Par_S_Code,
                        remark = Par_S_Code + "的二维码",
                        sacode = "test",
                        extra = extra
                    };
                    #endregion

                    #region vigo接口申请
                    var vigo = new ShareMarking.Interface.Qrcode_vigo(httpstr, signsecret);
                    var resultentity = vigo.UpdateQrcode(message);
                    #endregion

                    if (resultentity.IndexOf("成功") > 0)
                    {
                        #region 保存活动
                        entity.S_Name = Par_S_Name;
                        entity.S_Provinces = Par_S_Provinces;
                        entity.S_City = Par_S_City;
                        entity.S_Area = Par_S_Area;
                        entity.S_Region = Par_S_Region;
                        entity.ModifiedOn = DateTime.Now;
                        entity.A_wxTitle = Par_A_wxTitle;
                        entity.A_wxImgUrl = Par_A_wxImgUrl;
                        entity.A_wxDesc = Par_A_wxDesc;
                        entity.A_wxUrl = A_wxUrl;

                        result = qr_StoreService.Instance.Update_Entity(entity);
                        #endregion
                    }
                    else
                    {
                        ComLib.LogLib.Log4NetBase.Log("请求VIGO接口失败:err:" + resultentity);
                    }
                    #endregion
                }
            }
            if (result)
            {
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改qr_Store:" + entity.StoreCode); //记录日志
            }
            return result;
        }
        #endregion

        #region 保存按钮事件=============================

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (action == DTEnums.ActionEnum.Edit.ToString())
            { //修改
                //ChkAdminLevel("user_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    JscriptMsg("保存过程中发生错误！", "", "Error");
                    return;
                }
                JscriptMsg("修改成功！", "Index.aspx", "Success");
            }
            else //添加
            {
                //ChkAdminLevel("user_list", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    JscriptMsg("保存过程中发生错误！", "", "Error");
                    return;
                }
                JscriptMsg("添加成功！", "Index.aspx", "Success");
            }
        }

        #endregion
    }

}